<template>
    <div class="jianzhan-content">
        <Crumb name="出库"/>
        <div class="content">
            <Search>
                <el-input
                        v-model="key"
                        class="input"
                        size="small"
                        prefix-icon="el-icon-search"
                        placeholder="根据出库单查询"/>
            </Search>
            <div class="table-wrapper">
                <el-table border
                          @expand-change="getPartDetail"
                          stripe
                          row-key="id"
                          :data="stockList.slice((pageNum-1)*pageSize,pageNum*pageSize)"
                >
                    <el-table-column label="出库单号" prop="stockOutNum"/>
                    <el-table-column label="出库日期" prop="stockOutDateStr"/>
                    <el-table-column label="客户" prop="customer"/>
                    <el-table-column label="接收人" prop="receiver"/>
                    <el-table-column label="寄售单号" prop="salesOrderNum"/>
                    <el-table-column label="详情">
                        <template slot-scope="stock">
                            <el-button type="primary" size="small"  @click="showDetail(stock.row)">详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination    background
                                      :page-size="pageSize"
                                      @current-change="changePage"
                                      layout="prev, pager, next"
                                      :total="total"/>
                </div>
            </div>
        </div>
        <el-dialog title="出库详情" :visible.sync="dialogVisible" width="80%" >
            <el-form :model="stock" ref="stock" label-width="150px" :rules="rule" style="text-align: left">
                <el-form-item label="出库单号" prop="stockOutNum">
                   {{stock.stockOutNum}}
                </el-form-item>
                <el-form-item label="出库日期" prop="stockOutDateStr">
                   {{stock.stockOutDateStr}}
                </el-form-item>
                <el-form-item label="客户" prop="customer">
                    {{stock.customer}}
                </el-form-item>
                <el-form-item label="接收人" prop="receiver">
                    {{stock.receiver}}
                </el-form-item>
                <el-form-item label="类型" prop="applyType">
                    {{["服务","寄售"][stock.applyType]}}
                </el-form-item>
                <el-form-item v-if="stock.applyType === 0" label="工作单号" prop="workOrderNo">
                   {{stock.workOrderNo}}
                </el-form-item>
                <el-form-item v-if="stock.applyType === 1" label="寄售单号" prop="salesOrderNum">
                   {{stock.salesOrderNum}}
                </el-form-item>
                <el-form-item label="Warehouse" prop="warehouse">
                    {{stock.warehouseDesc}}
                </el-form-item>

                <Data-Base @deleteItem="deleteItem" :partList="partList" :edit="false"/>
            </el-form>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                        <el-button type="primary" @click="print">Print</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import Crumb from '../../components/common/crumb'
    import Search from '../../components/common/search'
    import DataBase from '../../components/part/spDataBase'
    import {mapActions} from 'vuex'
    import {
        getStockOutList,
        getPart,
        getStockOutDetail,
        getStockOutRecord
    } from "../../api/service";
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import spMixins from '../../util/spMixins'

    export default {
        name: "stock-out",
        mixins: [mixins, spMixins],
        data() {
            return {
                list: [],
                workNoList: [],
                rule: {
                    stockOutNum:[{required:true}],
                    customer:[{required:true}],
                    receiver:[{required:true}],
                    stockOutDateStr:[{required:true}],
                    applyType:[{required:true}],
                    workOrderNo:[{required:true}],
                    salesOrderNum:[{required:true}],
                    stockOutDetails:[{required:true}],
                    warehouse:[{required:true}],
                },
                stock: {
                    stockOutNum: '',
                    warehouse:'',
                    customer:'',
                    receiver:'',
                    stockOutDateStr: '',
                    applyType: '',
                    workOrderNo: '',
                    salesOrderNum: '',
                    stockOutDetails: []
                },
                key: '',
                dialogVisible: false,
                editable:true
            }
        },
        computed: {
            stockList() {
                return this.list.filter(item => item.stockOutNum.indexOf(this.key) > -1)
            }
        },
        created() {
            this._getStockOutList();
        },
        mounted(){
            this.$nextTick(() => {
                import('../../util/pdf.js').then(model => {
                    this.pdf = model.default;
                })
            })
        },
        methods: {
            print(){
                let body = [
                    [
                        {text: 'No', style: 'tableHeader', alignment: 'center'},
                        {text: '配件编号 / Part No', style: 'tableHeader', alignment: 'center'},
                        {text: 'Description', style: 'tableHeader', alignment: 'center'},
                        {text: '中文描述', style: 'tableHeader', alignment: 'center'},
                        {text: 'Qty', style: 'tableHeader', alignment: 'center'},
                        {text: 'Unit', style: 'tableHeader', alignment: 'center'},
                        {text: '备注／Remark', style: 'tableHeader', alignment: 'center'}
                    ],
                    // [{text: 'Service Item',colSpan:4, style: 'tableHeader', alignment: 'left'},{},{},{},{text: 'Service Fee',colSpan:4, style: 'tableHeader', alignment: 'left'},{},{},{}]
                ];
                const mainBody = this.partList.map((item, index) => {
                    return [index + 1, item.partsNumber, item.denomination, item.designation, item.number, 'pcs', '']
                });
                body = body.concat(mainBody);
                let total = 0;
                mainBody.forEach(item => {
                    total += item[4]
                });
                body = body.concat([['','','','',`Total:${total}`,'','']]);
                let doc = {
                    filename: 'QO',
                    pageSize: 'LEGAL',
                    pageMargins: [10, 200, 10, 60],
                    header: [
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '30%',
                                    text: [
                                        {
                                            text: 'PT INDONESIA EQUIPMENT LINE\n',
                                            style: 'header'
                                        },
                                        {
                                            text: "Leading in Service Innovation\n",
                                            style: 'subTitle'
                                        }
                                    ],

                                },
                                {
                                    width: '*',
                                    text: 'BUKTI PENGELURARAN SPAREPARTS\n配件出库单',
                                    style: 'title',
                                    alignment: 'right'
                                }
                            ],
                        },
                        {
                            margin: [20, 30, 0, 20],
                            columns: [
                                {
                                    width: '50%',
                                    text: [
                                        `日期／Date: ${this.stock.stockOutDateStr}\n`,
                                        `出库单号／Stock Out No: ${this.stock.stockOutNum}\n`,
                                        `用途/Apply Type: ${['Service','Consignment'][this.stock.applyType || 1]}\n`

                                    ],
                                    alignment:'center'
                                },
                                {
                                    width: '*',
                                    text: [
                                        `客户/Customer: ${this.stock.customer}\n`,
                                        `取件人/Receiver: ${this.stock.receiver}\n`,
                                        `申请单号/Request No:${this.stock.workOrderNo}\n`
                                    ],
                                    alignment:'center'
                                }
                            ]
                        }
                    ],
                    content: [
                        {
                            layout: 'lightHorizontalLines',
                            alignment: 'center',
                            table: {
                                // widths: ['auto', 'auto', 120, 120, 'auto', 'auto', 'auto'],
                                headerRows: 2,
                                body: body
                            }
                        },
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '*',
                                    text: [
                                        `领件人签字\nReceived By\n\n\n\n`,
                                        {
                                            text:'____________________',
                                        }
                                    ],
                                    alignment:'right',
                                }
                            ]
                        }
                    ],
                    footer: [
                        {
                            text: 'If you have any questions or concerns, please contact 0800-1581212',
                            width: '100%',
                            alignment: 'center'
                        },
                        {text: 'THANK YOU FOR YOUR BUSINESS! ', width: '100%', alignment: 'center'}
                    ],

                    defaultStyle: {
                        font: 'msyh'
                    },

                    styles: {
                        header: {
                            fontSize: 15,
                            bold: true
                        },
                        line:{
                            borderBottom:'2px solid #000',
                            marginTop:20,
                            width:200
                        },
                        title: {
                            fontWeight: 'light',
                            fontSize: 18,
                            bold: false
                        },
                        subTitle: {
                            fontSize: 12,
                            bold: true,
                            italic: true
                        }
                    }

                };
                this.$refs.stock.validate(valid=>{
                    if (valid) {
                        this.pdf && this.pdf.open(doc);
                    } else {
                        this.$notify.error('Please complete the form')
                    }
                })

            },

            async getPartDetail(r){
                if(r.partList){
                    return
                }
                const {status,data} = await getStockOutRecord(r.id);
                if(status===ERROR_OK) {
                    r.partList = data;
                    const index = this.list.findIndex(item=>item.id===r.id);
                    this.list.splice(index,1,r);
                }

            },

            async showDetail(stock) {
                this.dialogVisible = true;
                const {status,data} = await getStockOutDetail(stock.id);
                if(status === ERROR_OK ) {
                    this.stock = stock;
                    this.partList = data.map(part => {
                        return {
                            ...part.spareParts,
                            number: part.partsQuantity
                        }
                    })
                }
            },
            async _getStockOutList() {
                const {status, data} = await getStockOutList(1);
                if (status === ERROR_OK) {
                    this.list = data;
                    this.total = data.length
                }
            },

            async _getPart(workOrderNo) {
                const {status, data} = await getPart(workOrderNo);
                if (status === ERROR_OK) {
                    if(data.length === 0){
                        return
                    }
                    this.partList = data.map(part => {
                        return {
                            ...part.spareParts,
                            number: part.partsQuantity
                        }
                    })
                }
            },
        },
        watch: {
            stockList(list) {
                this.total = list.length
            }
        },
        components: {
            Crumb, Search, DataBase
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";
    .content {
        @include content
    }
</style>